<template>
  <div>
    <h3 text-center m-0 mb-20px>租户登录</h3>
    <el-form
      ref="tenantLoginFormRef"
      :model="tenantLoginFormData"
      :rules="tenantLoginRules"
      size="large"
      :validate-on-rule-change="false"
    >
      <!-- 租户编码 -->
      <el-form-item prop="tenantCode">
        <el-input v-model.trim="tenantLoginFormData.tenantCode" placeholder="请输入租户编码">
          <template #prefix>
            <el-icon><OfficeBuilding /></el-icon>
          </template>
        </el-input>
      </el-form-item>

      <!-- 用户名 -->
      <el-form-item prop="username">
        <el-input v-model.trim="tenantLoginFormData.username" placeholder="用户名">
          <template #prefix>
            <el-icon><User /></el-icon>
          </template>
        </el-input>
      </el-form-item>

      <!-- 密码 -->
      <el-tooltip :visible="isCapsLock" content="大写锁定已开启" placement="right">
        <el-form-item prop="password">
          <el-input
            v-model.trim="tenantLoginFormData.password"
            placeholder="密码"
            type="password"
            show-password
            @keyup="checkCapsLock"
            @keyup.enter="handleTenantLoginSubmit"
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
      </el-tooltip>

      <!-- 验证码 -->
      <el-form-item prop="captchaCode">
        <div flex>
          <el-input
            v-model.trim="tenantLoginFormData.captchaCode"
            placeholder="验证码"
            @keyup.enter="handleTenantLoginSubmit"
          >
            <template #prefix>
              <div class="i-svg:captcha" />
            </template>
          </el-input>
          <div cursor-pointer h="[40px]" w="[120px]" flex-center ml-10px @click="getCaptcha">
            <el-icon v-if="codeLoading" class="is-loading"><Loading /></el-icon>

            <img
              v-else
              object-cover
              border-rd-4px
              p-1px
              shadow="[0_0_0_1px_var(--el-border-color)_inset]"
              :src="captchaBase64"
              alt="code"
            />
          </div>
        </div>
      </el-form-item>

      <div class="flex-x-between w-full">
        <el-checkbox v-model="tenantLoginFormData.rememberMe">记住我</el-checkbox>
        <el-link type="primary" underline="never" @click="toOtherForm('login')">
          返回普通登录
        </el-link>
      </div>

      <!-- 登录按钮 -->
      <el-form-item>
        <el-button
          :loading="loading"
          type="primary"
          class="w-full"
          @click="handleTenantLoginSubmit"
        >
          租户登录
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script setup lang="ts">
import type { FormInstance } from "element-plus";
import AuthAPI, { type TenantLoginFormData } from "@/api/auth.api";
import router from "@/router";
import { useUserStore } from "@/store";
import { Auth } from "@/utils/auth";

const userStore = useUserStore();
const route = useRoute();

onMounted(() => getCaptcha());

const tenantLoginFormRef = ref<FormInstance>();
const loading = ref(false);
// 是否大写锁定
const isCapsLock = ref(false);
// 验证码图片Base64字符串
const captchaBase64 = ref();
// 记住我
const rememberMe = Auth.getRememberMe();

const tenantLoginFormData = ref<TenantLoginFormData>({
  tenantCode: "default",
  username: "admin",
  password: "123456",
  captchaKey: "",
  captchaCode: "",
  rememberMe,
});

const tenantLoginRules = computed(() => {
  return {
    tenantCode: [
      {
        required: true,
        trigger: "blur",
        message: "请输入租户编码",
      },
    ],
    username: [
      {
        required: true,
        trigger: "blur",
        message: "请输入用户名",
      },
    ],
    password: [
      {
        required: true,
        trigger: "blur",
        message: "请输入密码",
      },
      {
        min: 6,
        message: "密码长度至少6位",
        trigger: "blur",
      },
    ],
    captchaCode: [
      {
        required: true,
        trigger: "blur",
        message: "请输入验证码",
      },
    ],
  };
});

// 获取验证码
const codeLoading = ref(false);
function getCaptcha() {
  codeLoading.value = true;
  AuthAPI.getCaptcha()
    .then((data) => {
      tenantLoginFormData.value.captchaKey = data.captchaKey;
      captchaBase64.value = data.captchaBase64;
    })
    .finally(() => (codeLoading.value = false));
}

/**
 * 租户登录提交
 */
async function handleTenantLoginSubmit() {
  try {
    // 1. 表单验证
    const valid = await tenantLoginFormRef.value?.validate();
    if (!valid) return;

    loading.value = true;

    // 2. 执行租户登录
    await userStore.tenantLogin(tenantLoginFormData.value);

    // 3. 获取用户信息（包含用户角色，用于路由生成）
    await userStore.getUserInfo();

    // 4. 登录成功，简单跳转，让路由守卫处理后续逻辑
    const redirectPath = (route.query.redirect as string) || "/";

    // 使用push而不是replace，避免与路由守卫冲突
    await router.push(decodeURIComponent(redirectPath));
  } catch (error) {
    // 5. 统一错误处理
    getCaptcha(); // 刷新验证码
    console.error("租户登录失败:", error);
  } finally {
    loading.value = false;
  }
}

// 检查输入大小写
function checkCapsLock(event: KeyboardEvent) {
  // 防止浏览器密码自动填充时报错
  if (event instanceof KeyboardEvent) {
    isCapsLock.value = event.getModifierState("CapsLock");
  }
}

const emit = defineEmits(["update:modelValue"]);
function toOtherForm(type: "login" | "register" | "resetPwd") {
  emit("update:modelValue", type);
}
</script>

<style lang="scss" scoped></style>
